package com.fractalist.android.ads;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class AdView extends RelativeLayout {

	// private int state;

	private AdView m_view;

	private AdRequest m_request;
	private AdFractalist m_ad;
	private int m_currentContent = -1;

	private final int m_minFreshInterval = 15;
	private int m_freshInterval = 15;
	private boolean m_fade = true;
	private boolean m_showCloseButton = false;
	private View[] m_views;
	private ImageView m_closeButton;
	private ImageView m_adImageView = null;

	private AdViewClickListener m_clickListener;
	private CloseButtonClickListener m_closeButtonListener;
	private Handler m_stateHandler;

	private int m_failCount = 0;
	private int m_oldFreshInterval = 15;

	private String m_errorMsg;
	private Context myContext;

	// 设置属性
	public boolean getFadeImage() {
		return m_fade;
	}

	public void setFadeImage(boolean fade) {
		m_fade = fade;
	}

	public int getFreshInterval() {
		return m_freshInterval;
	}

	public void setFreshInterval(int interval) {
		if (interval < m_minFreshInterval) {
			interval = m_minFreshInterval;
		}
		if (m_freshInterval != interval) {
			m_freshInterval = interval;
			m_oldFreshInterval = interval;
		}
	}

	public boolean getShowCloseButton() {
		return m_showCloseButton;
	}

	public void setShowCloseButton(boolean showClose) {

		if (m_showCloseButton != showClose) {
			m_showCloseButton = showClose;
		}
	}

	public AdRequest getRequest() {
		return m_request;
	}

	public AdFractalist getAdFractalist() {
		return m_ad;
	}

	public String getError() {
		return m_errorMsg;
	}

	public void setStateHander(Handler stateHandler) {
		m_stateHandler = stateHandler;
	}

	// 启动、停止刷新广告
	public void restart() {
		try {
			if (freshTimer != null) {
				freshTimer.cancel();
				freshTimer.purge();
				freshTimer = null;
			}
			freshTimer = new Timer();
			freshTimer.schedule(new TaskFreshTimer(), 0, m_freshInterval * 1000);
			if (m_stateHandler != null) {
				Message message = new Message();
				message.what = 1;
				m_stateHandler.sendMessage(message);
			}

			// state = 1;
		} catch (Exception e) {
			m_errorMsg = e.getMessage();
		}
	}

	public void stop() {
		try {
			if (freshTimer != null) {
				freshTimer.cancel();
				freshTimer.purge();
				freshTimer = null;
				if (timer != null) {
					timer.cancel();
					timer.purge();
					timer = null;
				}
			}
			m_ad = null;
			m_view.removeAllViews();
			m_adImageView = null;
			m_views = null;
			System.gc();
			if (m_stateHandler != null) {
				Message message = new Message();
				message.what = 0;
				m_stateHandler.sendMessage(message);
			}

			// state = 0;
		} catch (Exception e) {
			m_errorMsg = e.getMessage();
		}
	}

	@Override
	protected void onWindowVisibilityChanged(int visibility) {
		if (visibility == View.VISIBLE) {
			this.restart();
		} else if (visibility == View.INVISIBLE || visibility == View.GONE) {
			this.stop();
		}
	}

	// 响应Close按钮
	private class CloseButtonClickListener implements OnClickListener {
		public void onClick(View v) {
			try {
				if (m_view != null) {
					m_view.stop();
				}
			} catch (Exception e) {
				m_errorMsg = e.getMessage();
			}
		}
	}

	// 响应点击广告
	private class AdViewClickListener implements OnClickListener {
		public void onClick(View v) {
			try {
				if (m_ad != null && m_ad.getContentCount() > 0 && m_currentContent >= 0
						&& m_currentContent < m_ad.getContentCount()) {
					AdContent content = m_ad.getContent(m_currentContent);
					if (content != null) {
						String url = content.getClickUrl();
						if (url.startsWith("http")) {
							Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
							getContext().startActivity(browser);
						} else {
							Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse("http://" + url));
							getContext().startActivity(browser);
						}
					}
				}
			} catch (Exception e) {
				m_errorMsg = e.getMessage();
			}
		}
	}

	// 使用线程下载广告内容
	Handler handlerThread = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what != 0) {
				m_failCount++;
			} else {
				m_failCount = 0;
				if (m_oldFreshInterval != m_freshInterval) {
					m_freshInterval = m_oldFreshInterval;
					m_view.stop();
					m_view.restart();
					return;
				}
			}

			if (m_failCount == 6) {
				if (m_freshInterval < 60) {
					m_freshInterval = 60;
					m_view.stop();
					m_view.restart();
					return;
				}
			}
			if (m_failCount == 3) {
				if (m_freshInterval < 30) {
					m_oldFreshInterval = m_freshInterval;
					m_freshInterval = 30;
					m_view.stop();
					m_view.restart();
					return;
				}
			}

			switch (msg.what) {
			case 0: // 成功
				// 设置广告显示窗口
				try {
					if (timer != null) {
						timer.cancel();
						timer.purge();
						timer = null;
					}

					if (m_ad != null) {
						m_views = new View[m_ad.getContentCount()];
						ViewGroup.LayoutParams layout = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
								ViewGroup.LayoutParams.WRAP_CONTENT);

						for (int i = 0; i < m_ad.getContentCount(); i++) {
							AdContent content = m_ad.getContent(i);
							if (content != null) {
								String type = content.getType();
								if (type.startsWith("image")) {
									byte[] bmpBuf = content.getContent();
									Bitmap bmp = BitmapFactory.decodeByteArray(bmpBuf, 0, bmpBuf.length);
									if (bmp != null) {
										ImageView imageView = new ImageView(m_view.getContext());
										imageView.setLayoutParams(layout);
										imageView.setBackgroundColor(Color.TRANSPARENT);
										int srcWidth = bmp.getWidth();
										int srcHeight = bmp.getHeight();
										int dstWidth = srcWidth;
										int dstHeight = srcHeight;
										if (m_request.getAdWidth() > 0) {
											dstWidth = m_request.getAdWidth();
										}
										if (dstWidth != srcWidth) {
											dstHeight = srcHeight * dstWidth / srcWidth;
										}
										bmp = Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, false);
										imageView.setImageBitmap(bmp);
										m_views[i] = imageView;
									} else {
										m_views[i] = null;
									}
								} else if (type.startsWith("video")) {
									m_views[i] = null;
								} else {
									m_views[i] = null;
								}
							}
						}

						if (m_showCloseButton && m_closeButton == null) {
							m_closeButton = new ImageView(m_view.getContext());
							RelativeLayout.LayoutParams l1 = new RelativeLayout.LayoutParams(
									RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
							l1.alignWithParent = true;
							l1.addRule(RelativeLayout.ALIGN_RIGHT);
							m_closeButton.setLayoutParams(l1);
							m_closeButton.setBackgroundColor(Color.TRANSPARENT);
							int cbID = m_view.getResources().getIdentifier("adclosebutton", "drawable",
									m_view.getContext().getPackageName());
							Bitmap closeBmp = BitmapFactory.decodeResource(m_view.getResources(), cbID);
							m_closeButton.setImageBitmap(closeBmp);
							m_closeButtonListener = new CloseButtonClickListener();
							m_closeButton.setOnClickListener(m_closeButtonListener);
						}

						Random ram = new Random();
						int aniType = Math.abs(ram.nextInt()) % 3;

						View addView = null;
						if (m_views != null && m_views.length > 0) {
							boolean hasView = false;
							for (int i = 0; i < m_views.length; i++) {
								if (m_views[i] != null) {
									hasView = true;
									break;
								}
							}
							if (hasView) {
								m_currentContent = (m_currentContent + 1) % m_views.length;
								while (m_views[m_currentContent] == null) {
									m_currentContent = (m_currentContent + 1) % m_views.length;
								}

								if (m_currentContent >= 0 && m_currentContent < m_views.length) {
									m_view.addView(m_views[m_currentContent]);
									addView = m_views[m_currentContent];
									if (m_fade && m_adImageView != null) {
										if (aniType == 0) {
											Animation anim = new AlphaAnimation(0.0f, 1.0f);
											anim.setDuration(500);
											addView.startAnimation(anim);
										} else if (aniType == 1) {
											Animation anim = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f,
													Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.0f);
											anim.setDuration(500);
											anim.setStartOffset(500);
											addView.startAnimation(anim);
										} else if (aniType == 2) {
											Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f,
													Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
													Animation.RELATIVE_TO_SELF, 0.0f);
											anim.setDuration(500);
											addView.startAnimation(anim);
										}
									}
								}
								if (m_showCloseButton && m_closeButton != null) {
									m_view.removeView(m_closeButton);
									m_view.addView(m_closeButton);
								}
							}
						}

						if (m_fade && m_adImageView != null) {
							if (aniType == 0) {
								Animation anim = new AlphaAnimation(1.0f, 0.0f);
								anim.setDuration(500);
								m_adImageView.startAnimation(anim);
							} else if (aniType == 1) {
								Animation anim = new ScaleAnimation(1.0f, 0.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f,
										Animation.RELATIVE_TO_SELF, 0.0f);
								anim.setDuration(500);
								m_adImageView.startAnimation(anim);
							} else if (aniType == 2) {
								Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
										Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f,
										Animation.RELATIVE_TO_SELF, 0.0f);
								anim.setDuration(500);
								m_adImageView.startAnimation(anim);
							}
						}
						if (m_adImageView != null) {
							m_view.removeView(m_adImageView);
						}
						m_adImageView = (ImageView) addView;

						if (m_stateHandler != null) {
							Message message = new Message();
							message.what = 10;
							m_stateHandler.sendMessage(message);
						}

						// 启动刷新显示计时器
						timer = new Timer();
						timer.schedule(new ViewTimerTask(), 0, m_ad.getInterval() * 1000);
						System.gc();
					}
				} catch (Exception e) {
					m_errorMsg = e.getMessage();
				}
				break;
			case 1: // 获取广告信息失败
				if (m_stateHandler != null) {
					Message message = new Message();
					message.what = 11;
					m_stateHandler.sendMessage(message);
				}
				break;
			case 2: // 解析JSON失败
				if (m_stateHandler != null) {
					Message message = new Message();
					message.what = 12;
					m_stateHandler.sendMessage(message);
				}
				break;
			case 3: // 获取显示图片（视频）数据失败
				if (m_stateHandler != null) {
					Message message = new Message();
					message.what = 13;
					m_stateHandler.sendMessage(message);
				}
				break;
			case 4: // 网络连接错误
				if (m_stateHandler != null) {
					Message message = new Message();
					message.what = 14;
					m_stateHandler.sendMessage(message);
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	public class AdThread extends Thread {
		public void run() {
			// 下载广告内容
			Message message = new Message();

			String requestAdd = m_request.getRequestAdd();
			String requestParams = m_request.getRequestParams();

			try {
				// 建立连接
				boolean isCmwap = false;
				/*
				 * ConnectivityManager conMan = (ConnectivityManager)
				 * m_view.getContext
				 * ().getSystemService(Context.CONNECTIVITY_SERVICE); if (conMan
				 * != null) { NetworkInfo.State wifi =
				 * conMan.getNetworkInfo(ConnectivityManager
				 * .TYPE_WIFI).getState(); NetworkInfo.State mobile =
				 * conMan.getNetworkInfo
				 * (ConnectivityManager.TYPE_MOBILE).getState(); if (wifi ==
				 * NetworkInfo.State.CONNECTED || wifi ==
				 * NetworkInfo.State.CONNECTING) { isCmwap = false; } else if
				 * (mobile == NetworkInfo.State.CONNECTED || mobile ==
				 * NetworkInfo.State.CONNECTING) { NetworkInfo mobileInfo =
				 * conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				 * String currentAPN = mobileInfo.getExtraInfo(); if
				 * (currentAPN.equalsIgnoreCase("cmwap")) { isCmwap = true; } }
				 * }
				 */
				URL url = new URL(requestAdd);
				HttpURLConnection httpConn = null;
				if (isCmwap) {
					Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.172", 80));
					httpConn = (HttpURLConnection) url.openConnection(proxy);
				} else {
					httpConn = (HttpURLConnection) url.openConnection();
				}

				// 设置连接属性
				httpConn.setDoOutput(true);// 使用 URL 连接进行输出
				httpConn.setDoInput(true);// 使用 URL 连接进行输入
				httpConn.setUseCaches(false);// 忽略缓存
				httpConn.setRequestMethod("POST");// 设置URL请求方法
				httpConn.setConnectTimeout(10000);

				byte[] requestStringBytes = requestParams.getBytes("UTF-8");
				httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
				httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
				httpConn.setRequestProperty("Charset", "UTF-8");

				// 建立输出流，并写入数据
				OutputStream outputStream = httpConn.getOutputStream();
				outputStream.write(requestStringBytes);
				outputStream.close();
				// 获得响应状态
				int responseCode = httpConn.getResponseCode();
				if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功
					// 当正确响应时处理数据
					StringBuffer sb = new StringBuffer();
					String readLine;
					BufferedReader responseReader;
					// 处理响应流，必须与服务器响应流输出的编码一致
					responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
					while ((readLine = responseReader.readLine()) != null) {
						sb.append(readLine).append("\n");
					}
					responseReader.close();

					try {
						AdFractalist newAd = new AdFractalist();
						JSONObject ob = new JSONObject(sb.toString());
						JSONObject ftad = ob.getJSONObject("ftad");
						newAd.setVersion(ftad.getString("version"));
						newAd.setResult(ftad.getInt("adclickresult"));
						JSONObject adContents = ftad.getJSONObject("adcontents");
						newAd.setInterval(adContents.getInt("interval"));
						JSONArray adContentArray = adContents.getJSONArray("adcontent");
						for (int i = 0; i < adContentArray.length(); i++) {
							JSONObject adContent = adContentArray.getJSONObject(i);
							if (adContent != null) {
								String contentType = adContent.getString("contenttype");
								String contentUrl = adContent.getString("adcontenturl");
								String contentDec = adContent.getString("addesc");
								String contentClickUrl = adContent.getString("adclickurl");
								byte[] content = null;
								// 获得Content
								url = new URL(contentUrl);
								try {
									String imageName = getImageName(contentUrl);
									InputStream is = openInputStreamFromCacheDir(myContext, imageName);
									if (is != null) {
										content = getContentsFromInputStream(is);
									} else {
										is = url.openStream();
										content = getContentsFromInputStream(is);
										saveBitmapToCacheDir(myContext, content, imageName);
									}
								} catch (IOException e) {
									m_errorMsg = e.getMessage();
									message.what = 2;
									handlerThread.sendMessage(message);
									return;
								}
								AdContent newContent = new AdContent(contentType, content, contentDec, contentClickUrl);
								newAd.addContent(newContent);
							}
						}
						m_ad = newAd;
					} catch (JSONException e) {
						m_errorMsg = e.getMessage();
						message.what = 1;
						handlerThread.sendMessage(message);
						return;
					}
				} else {
					message.what = 4;
					handlerThread.sendMessage(message);
					return;
				}
			} catch (Exception e) {
				m_errorMsg = e.getMessage();
				message.what = 3;
				handlerThread.sendMessage(message);
				return;
			}

			message.what = 0;
			handlerThread.sendMessage(message);
		}
	}

	private byte[] getContentsFromInputStream(InputStream is) throws IOException {
		// InputStream isContent = url.openStream();
		ByteArrayBuffer bufferContent = new ByteArrayBuffer(0);
		byte[] buf = new byte[256];
		int readCount = 0;
		do {
			readCount = is.read(buf, 0, buf.length);
			if (readCount > 0) {
				bufferContent.append(buf, 0, readCount);
			}
		} while (readCount > 0);
		return bufferContent.toByteArray();
	}

	// 截取URL的图片名称
	private String getImageName(String ImageURL) {
		String spStr[] = ImageURL.split("/");
		return spStr[spStr.length - 1];
	}

	private boolean saveBitmapToCacheDir(Context context, byte[] bitmap, String fileName) throws IOException {
		OutputStream os = null;
		try {
			File cacheDir = context.getCacheDir();
			File savedFile = new File(cacheDir.getPath() + File.separator + fileName);
			os = new FileOutputStream(savedFile);
			os.write(bitmap);
		} finally {
			close(os);
		}
		return false;
	}

	private InputStream openInputStreamFromCacheDir(Context context, String fileName) {
		InputStream is = null;
		try {
			File cacheDir = context.getCacheDir();
			File savedFile = new File(cacheDir.getPath() + File.separator + fileName);
			savedFile.setLastModified(System.currentTimeMillis());
			is = new FileInputStream(savedFile);
			return is;

		} catch (FileNotFoundException e) {
			return null;
		}
	}

	private static void close(Closeable c) {
		if (c != null) {
			try {
				c.close();
			} catch (IOException e) {
				// do nothing.
			}
		}
	}

	// 按间隔时间切换显示内容
	private void flushView() {
		try {
			if (m_views != null && m_views.length > 0) {
				Random ram = new Random();
				int aniType = Math.abs(ram.nextInt()) % 3;

				View addView = null;
				if (m_currentContent >= 0 && m_currentContent < m_views.length) {
					m_view.addView(m_views[m_currentContent]);
					addView = m_views[m_currentContent];
					if (m_fade && m_adImageView != null && m_views[m_currentContent] != null) {
						if (aniType == 0) {
							Animation anim = new AlphaAnimation(0.0f, 1.0f);
							anim.setDuration(500);
							addView.startAnimation(anim);
						} else if (aniType == 1) {
							Animation anim = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f,
									Animation.RELATIVE_TO_SELF, 0.0f);
							anim.setDuration(500);
							anim.setStartOffset(500);
							addView.startAnimation(anim);
						} else if (aniType == 2) {
							Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1.0f,
									Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
									Animation.RELATIVE_TO_SELF, 0.0f);
							anim.setDuration(500);
							addView.startAnimation(anim);
						}
					}
				}
				if (m_fade && m_adImageView != null) {
					if (aniType == 0) {
						Animation anim = new AlphaAnimation(1.0f, 0.0f);
						anim.setDuration(500);
						m_adImageView.startAnimation(anim);
					} else if (aniType == 1) {
						Animation anim = new ScaleAnimation(1.0f, 0.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f,
								Animation.RELATIVE_TO_SELF, 0.0f);
						anim.setDuration(500);
						m_adImageView.startAnimation(anim);
					} else if (aniType == 2) {
						Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
								1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
						anim.setDuration(500);
						m_adImageView.startAnimation(anim);
					}
				}
				if (m_adImageView != null) {
					m_view.removeView(m_adImageView);
				}
				m_adImageView = (ImageView) addView;

				if (m_showCloseButton && m_closeButton != null) {
					m_view.removeView(m_closeButton);
					m_view.addView(m_closeButton);
				}

				invalidate();
			}
		} catch (Exception e) {
			m_errorMsg = e.getMessage();
		}
	}

	private Timer timer = new Timer();
	Handler handlerTimer = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				try {
					if (m_views != null && m_views.length > 0) {
						boolean hasView = false;
						for (int i = 0; i < m_views.length; i++) {
							if (m_views[i] != null) {
								hasView = true;
								break;
							}
						}
						if (hasView) {
							int oldContent = m_currentContent;
							m_currentContent = (m_currentContent + 1) % m_views.length;
							while (m_views[m_currentContent] == null) {
								m_currentContent = (m_currentContent + 1) % m_views.length;
							}
							if (oldContent != m_currentContent) {
								flushView();
							}
						}
					}
				} catch (Exception e) {
					m_errorMsg = e.getMessage();
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	class ViewTimerTask extends TimerTask {
		public void run() {
			Message message = new Message();
			message.what = 0;
			handlerTimer.sendMessage(message);
		}
	}

	// 按时从服务器刷新
	private Timer freshTimer = new Timer();
	Handler handlerFreshTimer = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				new AdThread().start();
				break;
			}
			super.handleMessage(msg);
		}
	};

	class TaskFreshTimer extends TimerTask {
		public void run() {
			Message message = new Message();
			message.what = 0;
			handlerFreshTimer.sendMessage(message);
		}
	};

	public AdView(Context context) {
		super(context);
		init(context, null);
	}

	public AdView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context, attrs);
	}

	public AdView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(context, attrs);
	}

	private void init(Context context, AttributeSet attrs) {
		m_view = this;
		this.myContext = context;
		try {
			if (attrs != null) {
				String namespace = "http://schemas.android.com/apk/res/" + context.getPackageName();

				int backColor = attrs.getAttributeUnsignedIntValue(namespace, "backgroundColor", 0X00000000);
				this.setBackgroundColor(backColor);

				m_fade = attrs.getAttributeBooleanValue(namespace, "fadeImage", true);

				m_freshInterval = attrs.getAttributeIntValue(namespace, "freshInterval", 15);
				if (m_freshInterval < m_minFreshInterval) {
					m_freshInterval = m_minFreshInterval;
				}
				m_oldFreshInterval = m_freshInterval;

				m_showCloseButton = attrs.getAttributeBooleanValue(namespace, "showCloseButton", false);
			}
		} catch (Exception e) {
			m_errorMsg = e.getMessage();
		}

		this.setGravity(Gravity.RIGHT | Gravity.TOP);

		String strPID = "";

		try {
			PackageManager manager = context.getPackageManager();
			ApplicationInfo info = manager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			if (info != null) {
				try {
					strPID = "" + info.metaData.getInt("FRACTALIST_PUBLISHER_ID");
				} catch (ClassCastException ec) {
					strPID = info.metaData.getString("FRACTALIST_PUBLISHER_ID");
				}
				if (strPID == null || strPID.length() <= 0) {
					strPID = info.metaData.getString("FRACTALIST_PUBLISHER_ID");
				}
			}
		} catch (Exception e) {
			m_errorMsg = e.getMessage();
		}
		if (strPID == null || strPID.length() <= 0) {
			strPID = "0";
		}

		int iWidth = 240;
		int iHeight = 320;
		try {
			DisplayMetrics dm = context.getResources().getDisplayMetrics();
			if (dm != null) {
				iWidth = dm.widthPixels;
				iHeight = dm.heightPixels;
			}
		} catch (Exception e) {
			m_errorMsg = e.getMessage();
		}

		m_request = new AdRequest("1.0", strPID, iWidth, iHeight);

		try {
			WebView webview = new WebView(context);
			webview.layout(0, 0, 0, 0);
			WebSettings settings = webview.getSettings();
			if (settings != null) {
				m_request.setDeviceUA(settings.getUserAgentString());
			}

			m_request.setDeviceName(Build.DEVICE);
		} catch (Exception e) {
			m_errorMsg = e.getMessage();
		}

		try {
			TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			if (telephonyManager != null) {
				m_request.setDeviceID(telephonyManager.getDeviceId());
				m_request.setDeviceOS(telephonyManager.getDeviceSoftwareVersion());
				m_request.setUserID(telephonyManager.getLine1Number());
				m_request.setUserInfo(telephonyManager.getNetworkOperatorName());
			}
		} catch (Exception e) {
			m_errorMsg = e.getMessage();
		}

		m_clickListener = new AdViewClickListener();
		this.setOnClickListener(m_clickListener);

		restart();
		// freshTimer.schedule(new TaskFreshTimer(), 0, m_freshInterval * 1000);
	}

}
